#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //根节点名字
    ui->treeWidget->setHeaderLabel("动物");

    //新增顶层节点
    QTreeWidgetItem* item1=new QTreeWidgetItem();
    item1->setText(0,"猫");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2=new QTreeWidgetItem();
    item2->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(item2);
    //添加一些子节点
    QTreeWidgetItem* item3=new QTreeWidgetItem();
    item3->setText(0,"狸花猫");
    item1->addChild(item3);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_add_top_clicked()
{
    //获取输入框内容
    const QString& st=ui->lineEdit->text();
    //构造,添加
    QTreeWidgetItem* item=new QTreeWidgetItem();
    item->setText(0,st);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_add_cur_clicked()
{
    //获取当前选中
    QTreeWidgetItem* cur=ui->treeWidget->currentItem();
    if(cur==nullptr) return;

    //获取输入框内容
    const QString& st=ui->lineEdit->text();
    //构造,添加
    QTreeWidgetItem* item=new QTreeWidgetItem();
    item->setText(0,st);
    cur->addChild(item);
}

void Widget::on_del_cur_clicked()
{
    //获取当前选中
    QTreeWidgetItem* cur=ui->treeWidget->currentItem();
    if(cur==nullptr) return;
    else
    {
        //获取父元素
        QTreeWidgetItem* parent=cur->parent();
        if(parent==nullptr)//顶层元素
        {
            int index=ui->treeWidget->indexOfTopLevelItem(cur);
            ui->treeWidget->takeTopLevelItem(index);
        }
        else parent->removeChild(cur);
    }
}
